import api from "@/api";
// import router from "@/router";
import tool from "@/utils/tool";

/**
 *
 * 构建菜单
 */
// function buildMenus(routes) {
// 	if (!routes) {
// 		return [];
// 	}
// 	let menus = [];
// 	for (let route of routes) {
// 		if (!route.meta.hidden) {
// 			let menu = { ...route };
// 			// console.log("route", route);
// 			// router.resolve({ name: route.name });
// 			// menu.route = routeObject;
// 			menus.push(menu);
// 			if (menu.children && route.children.length > 0) {
// 				menu.children = buildMenus(route.children);
// 			}
// 		}
// 	}
// 	return menus;
// }
/**
 * 用户相关的设置
 */
export default {
	namespaced: true,
	state: {
		//动态路由
		menus: [],
		//用户详情
		userInfo: {},
		//是否已登录
		isLoggedIn: false,
		token: tool.data.get("TOKEN"),
	},
	getters: {
		menus(state) {
			return state.menus;
		},
		userInfo(state) {
			return state.userInfo;
		},
		token(state) {
			return state.token;
		},
	},
	mutations: {
		SET_MENUS(state, menus) {
			state.menus = menus;
		},
		SET_USERINFO(state, userInfo) {
			state.userInfo = userInfo;
		},
		SET_TOKEN(state, token) {
			state.token = token;
			if (token) {
				state.isLoggedIn = true;
				tool.data.set("TOKEN", token);
			} else {
				state.isLoggedIn = false;
				tool.data.remove("TOKEN");
			}
		},
	},
	actions: {
		//登录
		login({ commit }, data) {
			const { username, password } = data;
			return new Promise((resolved, reject) => {
				api.auth.token
					.post({ username: username.trim(), password: password })
					.then((res) => {
						if (res.code === 200) {
							//登录成功
							commit("SET_TOKEN", res.data.token, data.autologin);
							resolved();
						} else {
							reject(res.msg);
						}
					});
			});
		}, //登出
		loginOut({ commit }) {
			return new Promise((resolved) => {
				//TODO API
				commit("SET_TOKEN", null);
				resolved();
			});
		},
		//获取菜单
		fetchMenus() {
			return new Promise((resolved) => {
				api.user.menus.get().then((res) => {
					resolved(res.data);
					// commit("SET_MENUS", res.data);
				});
			});
		}, //设置菜单
		setMenus({ commit }, dynamicMenuRoutes) {
			//过滤掉隐藏menu

			// let menus = buildMenus(dynamicMenuRoutes);
			// console.log("setMenus", dynamicMenuRoutes, menus);
			commit("SET_MENUS", dynamicMenuRoutes);
		},
		//获取当前用户详情
		fetchUserInfo({ commit }) {
			let userInfoData = api.user.userInfo.get();
			userInfoData.then((userInfo) => {
				// console.log("fetchUserInfo", userInfo.data);
				commit("SET_USERINFO", userInfo.data);
			});
		},
	},
};
